package com.leetcode.No0901;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @program: Solution
 * @description: 股票价格跨度
 * @author: Wang Zhihua
 * @date: 2022-11-01
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner obj = new StockSpanner();
 * int param_1 = obj.next(price);
 */
public class StockSpanner2 {

    private Deque<Stock> stack;
    private int idx;

    public StockSpanner2() {
        stack = new ArrayDeque<>();
        idx = 0;
        stack.push(new Stock(Integer.MAX_VALUE, idx++));
    }

    public int next(int price) {
        Stock curStock = new Stock(price, idx++);
        while (curStock.price >= stack.peek().price) {
            stack.pop();
        }
        int ans = curStock.index - stack.peek().index;
        stack.push(curStock);
        return ans;
    }

    private class Stock {
        public Integer price;
        public Integer index;
        public Stock(Integer price, Integer index) {
            this.price = price;
            this.index = index;
        }
    }

    @Test
    public void test01() {
        StockSpanner2 stockSpanner = new StockSpanner2();
        stockSpanner.next(100); // 返回 1
        stockSpanner.next(80);  // 返回 1
        stockSpanner.next(60);  // 返回 1
        stockSpanner.next(70);  // 返回 2
        stockSpanner.next(60);  // 返回 1
        stockSpanner.next(75);  // 返回 4 ，因为截至今天的最后 4 个股价 (包括今天的股价 75) 都小于或等于今天的股价。
        stockSpanner.next(85);  // 返回 6
    }
}
